package cn.org.eshow.webapp.action;

import cn.org.eshow.bean.query.CartQuery;
import cn.org.eshow.model.Cart;
import cn.org.eshow.model.ProductItem;
import cn.org.eshow.model.User;
import cn.org.eshow.service.CartManager;
import cn.org.eshow.service.ProductItemManager;
import cn.org.eshow.service.ProductManager;
import cn.org.eshow.webapp.action.response.CartResponse;
import cn.org.eshow.webapp.util.RenderUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import static cn.org.eshow.webapp.util.RenderUtil.failure;

/**
 * 购物车API接口
 */
@AllowedMethods({"mine", "view", "delete", "deleteAll","updateByIds", "deleteByIds"})
public class CartAction extends ApiBaseAction<Cart> {

    private static final long serialVersionUID = 1L;

    @Autowired
    private CartManager cartManager;
    @Autowired
    private ProductManager productManager;
    @Autowired
    private ProductItemManager productItemManager;

    private List<Cart> carts = new ArrayList<Cart>();
    private Cart cart = new Cart();
    private CartQuery query = new CartQuery();

    private String ids;//购物车id数组(逗号隔开)
    private String quantities;//购物车数量数组(逗号隔开)

    /**
     * 我的购物车
     */
    public void mine() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        query.setUserId(user.getId());
        carts = cartManager.list(query);
        if (carts.isEmpty()) {
            RenderUtil.noData();
            return;
        }
        List<CartResponse> responses = new ArrayList<CartResponse>();
        for (Cart obj : carts) {
            CartResponse response = new CartResponse(obj);
            responses.add(response);
        }
        RenderUtil.list("获取成功", "carts", responses);
    }


    /**
     * 加入购物车
     */
    public void save() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        if (cart.getProductItem() == null || cart.getProductItem().getId() == null || cart.getQuantity() == null || cart.getQuantity() < 0) {
            RenderUtil.failure("缺少参数");
            return;
        }
        ProductItem productItem = productItemManager.get(cart.getProductItem().getId());
        if (productItem == null) {
            failure("非法参数");
            return;
        }
        cartManager.save(productItem.getProduct().getCategory(), productItem, cart.getQuantity(), user);

        RenderUtil.success("添加成功");

//        query.setUserId(user.getId());
//        query.setProductItemId(productItem.getId());
//        Cart old = cartManager.check(query);
//        if (old == null) {//若不存在
//            old = new Cart();
//            old.setPrice(productItem.getPrice());
//            old.setProduct(productItem.getProduct());
//            old.setOrigPrice(productItem.getPrice());
//            old.setAddTime(new Date());
//            old.setUser(user);
//            old = cartManager.save(old);
//            success(old.getId().toString());
//            return;
//        } else {//若已存在,则直接累加加
//            old.setQuantity(old.getQuantity() + cart.getQuantity());
//            old = cartManager.save(old);
//            success(old.getId().toString());
//            return;
//        }
    }

    /**
     * 批量修改
     */
    public void updateByIds() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        if (StringUtils.isNotEmpty(ids) && StringUtils.isNotEmpty(quantities)) {
            String[] cartIdArray = ids.split(",");//购物车ID数组
            String[] quantityArray = quantities.split(",");//购物车数量数组
            if (cartIdArray.length != quantityArray.length) {
                RenderUtil.failure("非法参数,两数组数量不一致");
                return;
            }
            List<Cart> carts = new ArrayList<Cart>();//购物车对象列表
            for (String cartId : cartIdArray) { //循环购物车ID数据
                Cart cart = cartManager.get(Integer.valueOf(cartId));
                if (cart == null) {
                    continue;
                } else {
                    if (!cart.getUser().getId().equals(user.getId()))
                        continue;//如果购物车商品不是当前用户则不处理
                    carts.add(cart);
                }
            }
            if (carts.isEmpty()) {
                RenderUtil.failure("购物车内暂无商品");
                return;
            }
            if (carts.size() != quantityArray.length) {
                RenderUtil.failure("非法参数,购物车ID中存在不是你的购物车");
                return;
            }

            for (int i=0;i<quantityArray.length;i++) {
                cartManager.update(carts.get(i),Integer.parseInt(quantityArray[i]));
            }
            RenderUtil.success("更新成功");
            return;
        }
        RenderUtil.failure("更新失败");
        return;

    }


    /**
     * 批量删除
     */
    public void deleteByIds() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        if (!StringUtils.isEmpty(ids)) {//cartIds走购物车流程
            String[] cartIdArray = ids.split(",");//购物车ID数组
            List<Cart> carts = new ArrayList<Cart>();//购物车对象列表
            for (String cartId : cartIdArray) { //循环购物车ID数据
                Cart cart = cartManager.get(Integer.valueOf(cartId));
                if (cart == null) {
                    continue;
                } else {
                    if (!cart.getUser().getId().equals(user.getId()))
                        continue;//如果购物车商品不是当前用户则不处理
                    carts.add(cart);
                }
            }
            if (carts.isEmpty()) {
                RenderUtil.failure("购物车内暂无商品");
                return;
            }

            for (Cart cart : carts) {
                cartManager.remove(cart);
            }
            RenderUtil.success("删除成功");
            return;
        }
        RenderUtil.failure("删除失败");
        return;

    }

    /**
     * 购物车删除
     */
    public void delete() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        if (id != null) {
            Cart old = cartManager.get(id);
            if (old != null) {
                cartManager.remove(old);
                RenderUtil.success("删除成功");
                return;
            }
        }
        RenderUtil.failure("删除失败");
        return;
    }

    /**
     * 购物车清空
     */
    public void deleteAll() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        query.setUserId(user.getId());
        List<Cart> carts = cartManager.list(query);
        for (Cart cart : carts) {
            cartManager.remove(cart);
        }
        RenderUtil.success("清空成功");
        return;
    }


    public List<Cart> getCarts() {
        return carts;
    }

    public void setCarts(List<Cart> carts) {
        this.carts = carts;
    }

    public Cart getCart() {
        return cart;
    }

    public void setCart(Cart cart) {
        this.cart = cart;
    }

    public CartQuery getQuery() {
        return query;
    }

    public void setQuery(CartQuery query) {
        this.query = query;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    public String getQuantities() {
        return quantities;
    }

    public void setQuantities(String quantities) {
        this.quantities = quantities;
    }
}